import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yishop/config/Config.dart';
import '../../utils/screen/ScreenAdapter.dart';
import 'package:dio/dio.dart';
import '../../model/HotProductsModel.dart';
import '../../widget/LoadingWidget.dart';

class Product extends StatefulWidget {
  Map arguments;

  Product({this.arguments});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Product();
  }
}

class _Product extends State<Product> {

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  //用于上拉分页
  ScrollController _scrollController = ScrollController();//listview 的控制器

  //分页
  int _page = 1;
  bool hasMore = true; //判断有没有数据

  //数据
  List _productList = [];
  //排序
  //价格升序 sort=price_1 价格降序 sort=price_-1 销量升序 sort=salecount_1 销量降序 sort=salecount_-1
  String _sort = '';

  @override
  void initState() {

    _getProductListData();
    //监听滚动条事件
    _scrollController.addListener(() {
      // print(_scrollController.position.pixels); //获取滚动条下拉的距离
      // print(_scrollController.position.maxScrollExtent); //获取整个页面的高度

      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {
        if(this.hasMore){
          _getProductListData();
        }

      }
    });
  }

  //显示加载中的圈圈
  Widget _showMore(index){

    if(this.hasMore){
      return (index==this._productList.length-1)?LoadingWidget():Text("");
    }else{
      return (index==this._productList.length-1)?Text("--我是有底线的--"):Text("");
    }
  }

  //获取商品列表数据
  _getProductListData() async{
    var api = '${Config.url}api/plist?cid=${widget.arguments['cid']}&page=${_page}&sort=${this._sort}';
    print(api);
    var reult = await Dio().get(api);
    var productList = new HotProductsModel.fromJson(reult.data);

    //判断是否是最后一页
    if (_productList.length < 9) {
      if(_page == 1){
        setState(() {
          this._productList.addAll(productList.result);
          this.hasMore = true;
          this._page++;
        });
      }else{
        setState(() {
          this._productList.addAll(productList.result);
          this.hasMore = false;
        });
      }

    }else{
      setState(() {
        this._productList.addAll(productList.result);
        this.hasMore = true;
        this._page++;
      });
    }
  }

  Future<void> _onRefresh() async {
    print("上拉刷新");
    await Future.delayed(Duration(milliseconds: 2000), () {
      print('请求数据完成');
      _page = 1;
      _productList = [];
      _getProductListData();
    });
  }

  //  加载中的圈圈
  Widget _getMoreWidget() {
    if (hasMore) {
      return Center(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '加载中...',
                style: TextStyle(fontSize: 16.0),
              ),
              CircularProgressIndicator(
                strokeWidth: 1.0,
              )
            ],
          ),
        ),
      );
    } else {
      return Center(
        child: Text('--我是有底线的--'),
      );
    }
  }

  Widget _getRadiusText(value) {
    return Container(
      height: ScreenAdapter.height(36),
      margin: EdgeInsets.only(right: 10),
      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
      //注意 如果Container里面加上decoration属性，color属性必须放decoration里面
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Color.fromRGBO(230, 230, 230, 0.9)),
      child: Text(value),
    );
  }


  //商品列表
  Widget _productListWidget(value) {
    if(value.length>0){
      return Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(top: ScreenAdapter.height(80)),
        child: ListView.builder(
            controller: _scrollController,
            itemCount: value.length,
            itemBuilder: (context, index) {
              //图片
              String sPic=value[index].pic;
              sPic=Config.url+sPic.replaceAll('\\', '/');
              return Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Container(
                        width: ScreenAdapter.width(180),
                        height: ScreenAdapter.height(180),
                        child: Image.network(
                          "${sPic}",
                          fit: BoxFit.cover,
                        ),
                      ),
                      Expanded(
                          flex: 1,
                          child: Container(
                            height: ScreenAdapter.height(180),
                            margin: EdgeInsets.all(ScreenAdapter.width(15)),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  "${value[index].title}",
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(),
                                ),
                                // Row(
                                //   children: <Widget>[_getRadiusText("256g")],
                                // ),
                                Text(
                                  "￥${value[index].price}",
                                  style: TextStyle(color: Colors.redAccent),
                                ),
                              ],
                            ),
                          ))
                    ],
                  ),
                  Divider(),
                  _showMore(index)
                ],
              );
            }),
      );
    }else{
      // return Center(
      //   child: Text("没有数据"),
      // );
      return LoadingWidget();
    }

  }

  //顶部导航栏
  Widget _productTopWidget() {
    return Positioned(
        top: 0,
        height: ScreenAdapter.height(80),
        width: ScreenAdapter.width(750),
        child: Container(
          width: ScreenAdapter.width(750),
          height: ScreenAdapter.height(80),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      width: ScreenAdapter.width(1),
                      color: Color.fromRGBO(233, 233, 233, 0.9)))),
          child: Row(
            children: <Widget>[
              Expanded(
                child: InkWell(
                  child: Padding(padding: EdgeInsets.fromLTRB(0, ScreenAdapter.width(16), 0,  ScreenAdapter.width(16)),
                    child: Text(
                      "综合",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.redAccent),
                    ),),
                  onTap: () {},
                ),
                flex: 1,
              ),
              Expanded(
                child: InkWell(
                  child: Padding(padding: EdgeInsets.fromLTRB(0, ScreenAdapter.width(16), 0,  ScreenAdapter.width(16)),
                    child: Text(
                      "销量",
                      textAlign: TextAlign.center,
                      style: TextStyle(),
                    ),),
                  onTap: () {},
                ),
                flex: 1,
              ),
              Expanded(
                child: InkWell(
                  child: Padding(padding: EdgeInsets.fromLTRB(0, ScreenAdapter.width(16), 0,  ScreenAdapter.width(16)),
                    child: Text(
                      "价格",
                      textAlign: TextAlign.center,
                      style: TextStyle(),
                    ),),
                  onTap: () {},
                ),
                flex: 1,
              ),
              Expanded(
                child: InkWell(
                  child: Padding(padding: EdgeInsets.fromLTRB(0, ScreenAdapter.width(16), 0,  ScreenAdapter.width(16)),
                    child: Text(
                      "筛选",
                      textAlign: TextAlign.center,
                      style: TextStyle(),
                    ),),
                  onTap: () {
                    _scaffoldKey.currentState.openEndDrawer();
                  },
                ),
                flex: 1,
              ),
            ],
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenAdapter.init(context);


    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text("${widget.arguments['title']}"),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        actions: <Widget>[
          Text("")
        ],
      ),
      endDrawer: Drawer(
        child: Center(
          child: Text("筛选功能"),
        ),
      ),
      // body: Text("Product:${widget.arguments}"),
      body: Stack(
        children: <Widget>[
          _productListWidget(this._productList),
          _productTopWidget(),
        ],
      ),
    );
  }
}
